<template>
  <div class="ai-view">
    <!-- AI导诊区域 -->
    <section class="ai-section">
      <div class="ai-container">
        <div class="ai-header">
          <h1 class="ai-title">AI智能导诊</h1>
          <p class="ai-subtitle">描述您的症状，智能推荐就诊科室，为您提供专业就医指导</p>
        </div>
        
        <div class="ai-intro">
          <p>您好！我是您的AI健康助手。请详细描述您当前的症状、不适部位、持续时间及伴随症状，我将为您提供初步的医疗建议和科室推荐。</p>
        </div>
        
        <div class="ai-chat-container">
          <div class="ai-chat-header">
            <div class="ai-avatar">
              <i class="fas fa-robot"></i>
            </div>
            <div>
              <div class="ai-chat-title">AI健康助手</div>
              <div class="ai-chat-status">在线 · 为您服务</div>
            </div>
          </div>
          
          <div class="ai-chat-messages" id="chat-messages">
            <div class="message ai-message">
              您好！我是安心医疗AI助手，请问您有什么不适症状需要咨询？
              <div class="options-container">
                <div class="option-btn" @click="selectSymptom('头痛')">头痛</div>
                <div class="option-btn" @click="selectSymptom('发热')">发热</div>
                <div class="option-btn" @click="selectSymptom('咳嗽')">咳嗽</div>
                <div class="option-btn" @click="selectSymptom('腹痛')">腹痛</div>
              </div>
            </div>
          </div>
          
          <div class="ai-chat-input">
            <input type="text" class="ai-input" v-model="userMessage" placeholder="请描述您的症状..." @keypress="handleKeyPress">
            <button class="ai-send-btn" @click="sendMessage">
              <i class="fas fa-paper-plane"></i>
            </button>
          </div>
        </div>
        
        <div class="result-card" :style="{ display: showResult  ? 'block' : 'none' }">
          <div class="result-header">
            <div class="result-icon">
              <i class="fas fa-stethoscope"></i>
            </div>
            <h2 class="result-title">就诊建议</h2>
          </div>
          
          <div class="recommendation-box">
            <h3 class="recommendation-title">根据您的描述，我们建议您优先考虑以下科室：</h3>
            
            <div class="department-list">
              <div 
                class="department-card" 
                v-for="dept in recommendedDepartments" 
                :key="dept"
              >
                <div class="department-name">{{ dept }}</div>
                <div class="department-desc">主治与"{{ currentSymptom }}"相关的疾病</div>
                <button class="btn btn-primary" style="padding: 8px 15px;">
                  <i class="fas fa-calendar-check"></i> 预约挂号
                </button>
              </div>
            </div>
          </div>
          
          <div class="recommendation-box">
            <h3 class="recommendation-title">健康建议</h3>
            <ul style="margin-left: 20px; margin-top: 15px;">
              <li 
                style="margin-bottom: 10px;" 
                v-for="(advice, index) in currentRecommendations" 
                :key="index"
              >
                {{ advice }}
              </li>
            </ul>
          </div>
          
          <div class="actions">
            <button class="btn btn-primary" @click="resetConsultation">
              <i class="fas fa-sync-alt"></i> 重新咨询
            </button>
            <button class="btn btn-outline">
              <i class="fas fa-download"></i> 保存建议
            </button>
            <button class="btn btn-outline">
              <i class="fas fa-share-alt"></i> 分享结果
            </button>
          </div>
        </div>
      </div>
    </section>
    
    <!-- 返回顶部按钮 -->
    <div class="floating-btn" @click="scrollToTop">
      <i class="fas fa-arrow-up"></i>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue';

// 状态管理
const userMessage = ref('');
const showResult  = ref(false);
const currentSymptom = ref('');
const recommendedDepartments = ref<string[]>([]);
const currentRecommendations = ref<string[]>([]);

// 预设的科室数据
const departments = {
  '头痛': ['神经内科', '普通内科'],
  '发热': ['普通内科', '感染科'],
  '咳嗽': ['呼吸内科', '普通内科'],
  '腹痛': ['消化内科', '普通外科'],
  '胸闷': ['心内科', '呼吸内科'],
  '头晕': ['神经内科', '心内科'],
  '皮疹': ['皮肤科', '过敏反应科'],
  '关节痛': ['风湿免疫科', '骨科']
};

// 预设的建议数据
const recommendations = {
  '头痛': [
    '注意休息，保证充足睡眠',
    '保持水分补充，避免脱水',
    '如头痛剧烈或持续加重，建议及时就医',
    '避免过度使用电子产品，注意用眼卫生'
  ],
  '发热': [
    '多喝水，保持充足水分',
    '适当休息，避免劳累',
    '物理降温（温水擦浴）',
    '如体温超过38.5℃，可考虑使用退热药'
  ],
  '咳嗽': [
    '多喝温水，保持喉咙湿润',
    '避免刺激性食物和烟酒',
    '注意室内空气流通和湿度',
    '如咳嗽伴有胸痛或呼吸困难，请及时就医'
  ]
};

// 发送消息
const sendMessage = () => {
  const message = userMessage.value.trim();
  if (message) {
    addUserMessage(message);
    userMessage.value = '';
    
    // AI回复
    setTimeout(() => {
      aiResponse(message);
    }, 1000);
  }
};

// 选择症状
const selectSymptom = (symptom: string) => {
  addUserMessage(symptom);
  setTimeout(() => {
    aiResponse(symptom);
  }, 800);
};

// 添加用户消息
const addUserMessage = (message: string) => {
  const chatMessages = document.getElementById('chat-messages');
  if (chatMessages) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message user-message';
    messageDiv.textContent = message;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }
};

// 添加AI消息
const addAiMessage = (htmlContent: string) => {
  const chatMessages = document.getElementById('chat-messages');
  if (chatMessages) {
    const messageDiv = document.createElement('div');
    messageDiv.className = 'message ai-message';
    messageDiv.innerHTML = htmlContent;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
  }
};

// AI回复
const aiResponse = (message: string) => {
  let response = '';
  let foundSymptom = '';
  
  // 检查症状关键词
  for (const symptom in departments) {
    if (message.includes(symptom)) {
      foundSymptom = symptom;
      break;
    }
  }
  
  if (foundSymptom) {
    currentSymptom.value = foundSymptom;
    response = `根据您描述的"${foundSymptom}"症状，建议您考虑以下科室：${departments[foundSymptom].join('、')}。`;
    
    // 添加选项
    response += `您想了解关于"${foundSymptom}"的更多信息吗？`;
    
    const messageHtml = `
      ${response}
      <div class="options-container">
        <div class="option-btn" onclick="showResultDetails('${foundSymptom}')">查看"${foundSymptom}"详情</div>
        <div class="option-btn" onclick="newConsultation()">咨询其他症状</div>
      </div>
    `;
    
    addAiMessage(messageHtml);
  } else {
    response = '抱歉，我没有理解您的症状描述。您可以尝试更详细地描述您的症状，或者从以下常见症状中选择：';
    
    const optionsHtml = ['头痛', '发热', '咳嗽', '腹痛', '胸闷', '头晕']
      .map(symptom => `<div class="option-btn" onclick="selectSymptom('${symptom}')">${symptom}</div>`)
      .join('');
    
    addAiMessage(`${response}<div class="options-container">${optionsHtml}</div>`);
  }
};

// 显示结果卡片
const showResultDetails = (symptom: string) => {
  currentSymptom.value = symptom;
  recommendedDepartments.value = departments[symptom] || [];
  currentRecommendations.value = recommendations[symptom] || [
    '建议您多休息，避免劳累',
    '保持充足的水分摄入',
    '如症状持续加重，请及时就医',
    '避免自行使用未经医生指导的药物'
  ];
  
  showResult.value = true;
  
  // 滚动到结果
  const resultCard = document.querySelector('.result-card');
  if (resultCard) {
    resultCard.scrollIntoView({ behavior: 'smooth' });
  }
};

// 重新咨询
const resetConsultation = () => {
  const chatMessages = document.getElementById('chat-messages');
  if (chatMessages) {
    chatMessages.innerHTML = `
      <div class="message ai-message">
        您好！我是安心医疗AI助手，请问您有什么不适症状需要咨询？
        <div class="options-container">
          <div class="option-btn" onclick="selectSymptom('头痛')">头痛</div>
          <div class="option-btn" onclick="selectSymptom('发热')">发热</div>
          <div class="option-btn" onclick="selectSymptom('咳嗽')">咳嗽</div>
          <div class="option-btn" onclick="selectSymptom('腹痛')">腹痛</div>
        </div>
      </div>
    `;
  }
  
  showResult.value = false;
  currentSymptom.value = '';
  recommendedDepartments.value = [];
  currentRecommendations.value = [];
};

// 新咨询
const newConsultation = () => {
  addAiMessage('请描述您的其他症状。');
  showResult.value = false;
};

// 按Enter发送消息
const handleKeyPress = (event: KeyboardEvent) => {
  if (event.key === 'Enter') {
    sendMessage();
  }
};

// 返回顶部
const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
};

// 处理全局函数
const setupGlobalFunctions = () => {
  (window as any).selectSymptom = selectSymptom;
  (window as any).showResultDetails = showResultDetails;
  (window as any).newConsultation = newConsultation;
};

// 监听滚动显示返回顶部按钮
const handleScroll = () => {
  const floatingBtn = document.querySelector('.floating-btn');
  if (floatingBtn) {
    if (window.scrollY > 500) {
      floatingBtn.style.display = 'flex';
    } else {
      floatingBtn.style.display = 'none';
    }
  }
};

// 生命周期钩子
onMounted(() => {
  setupGlobalFunctions();
  window.addEventListener('scroll', handleScroll);
  // 初始隐藏结果卡片
  showResult.value = false;
});

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll);
});
</script>

<style lang="scss">
// AI导诊区域
.ai-section {
  padding: 80px 8% 60px;
  max-width: 1200px;
  margin: 0 auto;
}

.ai-container {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.ai-header {
  text-align: center;
  margin-bottom: 20px;
}

.ai-title {
  font-family: 'Poppins', sans-serif;
  font-size: 2.5rem;
  color: var(--primary-blue);
  margin-bottom: 15px;
}

.ai-subtitle {
  font-size: 1.1rem;
  color: var(--text-medium);
  max-width: 700px;
  margin: 0 auto;
}

.ai-intro {
  text-align: center;
  margin-bottom: 30px;
}

// 聊天界面
.ai-chat-container {
  background: white;
  border-radius: 20px;
  box-shadow: var(--shadow);
  overflow: hidden;
  display: flex;
  flex-direction: column;
  height: 600px;
}

.ai-chat-header {
  background: var(--primary-blue);
  color: white;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.ai-avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: var(--accent-teal);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.ai-chat-title {
  font-size: 1.5rem;
  font-weight: 600;
}

.ai-chat-status {
  font-size: 0.9rem;
  opacity: 0.8;
}

.ai-chat-messages {
  flex: 1;
  padding: 25px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  max-width: 80%;
  padding: 15px 20px;
  border-radius: 18px;
  position: relative;
  animation: fadeIn 0.3s ease-out;
}

.ai-message {
  background: var(--light-blue);
  border-bottom-left-radius: 5px;
  align-self: flex-start;
}

.user-message {
  background: var(--primary-blue);
  color: white;
  border-bottom-right-radius: 5px;
  align-self: flex-end;
}

.options-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 15px;
}

.option-btn {
  padding: 8px 15px;
  background: white;
  border: 1px solid var(--primary-blue);
  color: var(--primary-blue);
  border-radius: 20px;
  font-size: 0.9rem;
  cursor: pointer;
  transition: var(--transition);
}

.option-btn:hover {
  background: var(--primary-blue);
  color: white;
}

.ai-chat-input {
  display: flex;
  padding: 20px;
  background: var(--light-gray);
  border-top: 1px solid var(--medium-gray);
}

.ai-input {
  flex: 1;
  padding: 12px 20px;
  border-radius: 30px;
  border: 1px solid var(--medium-gray);
  font-size: 1rem;
  outline: none;
  transition: var(--transition);
}

.ai-input:focus {
  border-color: var(--primary-blue);
  box-shadow: 0 0 0 0.2rem rgba(13, 110, 253, 0.25);
}

.ai-send-btn {
  margin-left: 15px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background: var(--primary-blue);
  color: white;
  border: none;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: var(--transition);
}

.ai-send-btn:hover {
  background: var(--dark-blue);
  transform: scale(1.05);
}

// 结果卡片
.result-card {
  background: white;
  border-radius: 20px;
  padding: 30px;
  box-shadow: var(--shadow);
  margin-top: 40px;
}

.result-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid var(--medium-gray);
}

.result-icon {
  width: 60px;
  height: 60px;
  border-radius: 15px;
  background: var(--gradient-blue);
  color: white;
  font-size: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.result-title {
  font-family: 'Poppins', sans-serif;
  font-size: 1.8rem;
  color: var(--primary-blue);
}

.recommendation-box {
  background: var(--light-blue);
  border-radius: 15px;
  padding: 25px;
  margin-bottom: 25px;
}

.recommendation-title {
  font-size: 1.3rem;
  margin-bottom: 15px;
  color: var(--text-dark);
  font-weight: 600;
}

.department-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin: 20px 0;
}

.department-card {
  flex: 1;
  min-width: 200px;
  background: white;
  border-radius: 15px;
  padding: 20px;
  box-shadow: var(--shadow-sm);
  border-left: 4px solid var(--accent-teal);
  transition: var(--transition);
}

.department-card:hover {
  transform: translateY(-5px);
  box-shadow: var(--shadow);
}

.department-name {
  font-size: 1.2rem;
  font-weight: 600;
  color: var(--text-dark);
  margin-bottom: 10px;
}

.department-desc {
  font-size: 0.9rem;
  color: var(--text-medium);
  margin-bottom: 15px;
}

.actions {
  display: flex;
  gap: 15px;
  margin-top: 30px;
}

// 返回顶部按钮
.floating-btn {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: var(--primary-blue);
  color: var(--white);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  box-shadow: 0 10px 25px rgba(13, 110, 253, 0.5);
  cursor: pointer;
  transition: var(--transition);
  z-index: 1000;
  display: none;
}

.floating-btn:hover {
  transform: scale(1.1);
  background: var(--dark-blue);
}

// 动画效果
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.1); }
  100% { transform: scale(1); }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 响应式设计
@media (max-width: 768px) {
  .ai-title {
    font-size: 2rem;
  }
  
  .ai-chat-container {
    height: 500px;
  }
  
  .department-list {
    flex-direction: column;
  }
  
  .message {
    max-width: 95%;
  }
}
</style>